import sys
import datetime
import logging
from os.path import join

# 使用单列模式来保证多个模块调用时, 只有一个代码
class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances.keys():
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class HanChLog:
    __metaclass__ = Singleton
    _loggers = {}

    def get_log(self, file_name, logger_name=None, logger_level=logging.DEBUG):
        self.file_name = file_name
        self.logger = logging.getLogger(logger_name)
        self.logger.setLevel(logger_level)
        # FileHandler: 将格式化的日志记录写入磁盘文件的处理程序类
        # 将格式化的日志记录写入磁盘文件的处理程序
        handler = logging.FileHandler(self.file_name, 'a', encoding='utf-8')
        handler.setLevel(logging.DEBUG)
        formater = logging.Formatter('%(asctime)s - %(filename)s - line:%(lineno)d -'
                                     ' %(levelname)s - %(message)s -%(process)s')

        handler.setFormatter(formater)
        self.logger.addHandler(handler)
        stdout_handler = logging.StreamHandler(sys.stdout)
        logShow = logging.getLogger()
        logShow.addHandler(stdout_handler)

    def info(self, msg):
        self.logger.info(msg)

    def debug(self, msg):
        self.logger.debug(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def critical(self, msg):
        self.logger.critical(msg)


logger = HanChLog()
